window.addEventListener('load', () => {
    let app = document.getElementById('app');
    let searchInput = document.querySelector('.search-input');

    // 搜索框聚焦常驻
    searchInput.addEventListener('focus', function () {
        this.parentNode.classList.add('active');
    });
    searchInput.addEventListener('blur', function () {
        this.parentNode.classList.remove('active');
    });

    // 开关侧边栏
    let toggleAside = document.getElementById('toggle-aside');

    toggleAside.addEventListener('click', function () {
        let isFolded = app.classList.toggle('aside-folded');
        let asideStrong = app.querySelector('strong[data-unfold-text]');
        let asideUsefulItemArr = [...app.querySelectorAll('.left-aside li a span'), ...app.querySelectorAll('.left-aside li a .toggle-fold')];

        if (isFolded) {
            this.children[0].className = 'fas fa-ellipsis-v';
            asideStrong.innerHTML = asideStrong.dataset.foldedText;
            asideUsefulItemArr.forEach(item => {
                item.style.display = 'none';
                // 优化侧边栏动画效果
                setTimeout(() => {
                    // 多行文字垂直居中: display: table-cell; vertical-align: middle;
                    item.style.display = 'table-cell';
                }, 300);
            });
        } else {
            this.children[0].className = 'fas fa-bars';
            asideUsefulItemArr.forEach(item => {
                item.style.display = 'none';
            });
            // 优化侧边栏动画效果
            setTimeout(() => {
                asideStrong.innerHTML = asideStrong.dataset.unfoldText;
                asideUsefulItemArr.forEach(item => {
                    item.style.display = 'initial';
                });
            }, 150);
        }
    });

    let toggleFoldArr = document.querySelectorAll('.toggle-fold');
    [...toggleFoldArr].forEach(item => {
        item.parentNode.addEventListener('click', function () {
            this.parentNode.classList.toggle('active');
        });
    });

    // 修复页脚
    let mainContent = document.querySelector('.main-content');
    let mainWrapper = mainContent.querySelector('.wrapper');
    // window.addEventListener('resize', fixFooter);
    // function fixFooter() {
    //     mainWrapper.style.position = mainContent.offsetHeight > mainWrapper.offsetHeight ? 'initial' : 'relative';
    // }
    // fixFooter();

    // 动画效果返回顶部
    let backTop = document.querySelector('.back-top');
    mainContent.addEventListener('scroll', function () {
        if (this.scrollTop > 60) backTop.classList.add('show');
        else backTop.classList.remove('show');
    })

    backTop.addEventListener('click', () => {
        scrollAnimate(mainContent, 0);
    });

    function scrollAnimate(obj, target) {
        clearInterval(window.scrollAnimateTimer);
        window.scrollAnimateTimer = setInterval(function () {
            if (obj.scrollTop === target) {
                clearInterval(window.scrollAnimateTimer);
            }

            var step = (target - obj.scrollTop) / 10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            obj.scroll(0, obj.scrollTop + step);
        }, 5);
    }

    // 音乐播放器模块
    let musicPlayer = document.querySelector('.music-player');
    let audio = musicPlayer.getElementsByTagName('audio')[0];
    let duration = audio?.duration;
    let musicList = [
        {
            title: '終点の先が在るとするならば。',
            author: ' - ツユ',
            cover: 'upload/music_cover/music01.jpg',
            src: 'media/audio/music01.mp3'
        },
        {
            title: 'ニュートンダンス',
            author: ' - ナユタン星人 × Chinozo',
            cover: 'upload/music_cover/music02.jpg',
            src: 'media/audio/music02.mp3'
        },
        {
            title: 'シェーマ',
            author: ' - Chinozo × v flower',
            cover: 'upload/music_cover/music03.jpg',
            src: 'media/audio/music03.mp3'
        },
        {
            title: 'エリート',
            author: ' - Chinozo',
            cover: 'upload/music_cover/music04.jpg',
            src: 'media/audio/music04.mp3'
        },
        {
            title: 'TAMAYA',
            author: ' - Chinozo × v flower',
            cover: 'upload/music_cover/music05.jpg',
            src: 'media/audio/music05.mp3'
        }
    ]
    audio.volume = 0.03;

    audio.addEventListener('canplay', () => {
        duration = audio.duration;
    });

    (() => {
        let currentMusic = 0;
        let coverImg = musicPlayer.querySelector('.music-cover').children[0];
        // 控制面板
        let control = musicPlayer.querySelector('.music-control');
        let prevBtn = control.querySelector('.prev');
        let togglPauseBtn = control.querySelector('.toggle-pause');
        let nextBtn = control.querySelector('.next');
        // 音量控件
        let volume = control.querySelector('.volume');
        let volumeBar = volume.querySelector('.volume-bar');
        let volumeSize = volume.querySelector('.volume-size');
        // 进度条
        let progressBar = control.querySelector('.progress-bar');
        let fakeProgressBar = progressBar.querySelector('.fake-progress-bar');
        let progress = progressBar.querySelector('.progress');
        let audioTimer;
        togglPauseBtn.children[0].className = audio.paused ? 'fas fa-play' : 'fas fa-pause';

        // 进度条动效
        function runProgressBar() {
            let currentTime = audio.currentTime;
            let percentage = currentTime / duration;

            progress.style.width = percentage * 100 + '%';
        }

        // 暂停 / 播放
        togglPauseBtn.addEventListener('click', function () {
            if (audio.paused) {
                audio.play();
            } else {
                audio.pause();
            }
        });

        // 上一首 / 下一首
        prevBtn.addEventListener('click', () => {
            currentMusic--;
            currentMusic = currentMusic < 0 ? musicList.length - 1 : currentMusic;
            reloadMusic();
        });

        nextBtn.addEventListener('click', () => {
            currentMusic++;
            currentMusic = currentMusic >= musicList.length ? 0 : currentMusic;
            reloadMusic();
        });

        function reloadMusic() {
            let isPausedBefore = audio.paused;
            audio.src = musicList[currentMusic]['src'];
            coverImg.src = musicList[currentMusic]['cover'];
            musicPlayer.querySelector('.music-title').innerHTML = musicList[currentMusic]['title'];
            musicPlayer.querySelector('.music-author').innerHTML = musicList[currentMusic]['author'];
            !isPausedBefore && audio.play();
        }

        // 点击进度条
        fakeProgressBar.addEventListener('click', function (e) {
            let percentage = e.offsetX / this.offsetWidth;
            audio.currentTime = percentage * duration;
            progress.style.width = percentage * 100 + '%';
        });

        // 拖动进度条
        fakeProgressBar.addEventListener('mousedown', function (e) {
            if (e.button === 0) {
                document.addEventListener('mousemove', move);
                document.addEventListener('mouseup', () => {
                    document.removeEventListener('mousemove', move);
                });

                function move(e) {
                    let percentage = e.offsetX / progressBar.offsetWidth;
                    percentage = percentage < 0 ? 0 : percentage;
                    percentage = percentage > 1 ? 1 : percentage;
                    audio.currentTime = percentage * duration;
                    progress.style.width = percentage * 100 + '%';
                }
            }
        });

        fakeProgressBar.addEventListener('mouseout', function (e) {
            progressBar.classList.remove('active');
        });

        // 点击修改音量
        volumeBar.addEventListener('click', function (e) {
            let percentage = (this.offsetHeight - e.pageY + 3) / this.offsetHeight;
            audio.volume = percentage;
        });

        // 拖动修改音量
        volumeBar.addEventListener('mousedown', function (e) {
            if (e.button === 0) {
                document.addEventListener('mousemove', move);
                document.addEventListener('mouseup', () => {
                    document.removeEventListener('mousemove', move);
                });

                function move(e) {
                    let percentage = (volumeBar.offsetHeight - e.pageY + 3) / volumeBar.offsetHeight;
                    percentage = percentage < 0 ? 0 : percentage;
                    percentage = percentage > 1 ? 1 : percentage;
                    audio.volume = percentage;
                }
            }
        });

        audio.addEventListener('volumechange', function () {
            volumeSize.style.height = this.volume * 100 + '%';
            if (this.volume === 0) {
                volume.children[0].className = 'fas fa-volume-off';
            } else if (this.volume < 0.7) {
                volume.children[0].className = 'fas fa-volume-down';
            } else if (this.volume >= 0.7) {
                volume.children[0].className = 'fas fa-volume-up';
            }
        })

        audio.addEventListener('play', () => {
            setTimer();
            togglPauseBtn.children[0].className = 'fas fa-pause';
            coverImg.style.animationPlayState = 'running';
        });

        audio.addEventListener('pause', () => {
            clearInterval(audioTimer);
            togglPauseBtn.children[0].className = 'fas fa-play';
            coverImg.style.animationPlayState = 'paused';
        });

        audio.addEventListener('ended', () => {
            nextBtn.click();
            this.play();
        });

        function setTimer() {
            // clearInterval(audioTimer);
            audioTimer = setInterval(() => {
                runProgressBar();
            }, 500);
        }

    })();
});

